package com.xiaowu.system.manager;


import com.xiaowu.common.core.constants.CacheConstants;
import com.xiaowu.common.redis.service.RedisService;
import com.xiaowu.common.redis.service.RedissonLockService;
import com.xiaowu.common.core.constants.CacheLockConstants;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class QuestionCacheManager {

    @Autowired
    private RedissonLockService redissonLockService;

    @Autowired
    private RedisService redisService;

    @Async(value = "threadPoolTaskExecutor")
    public void addCache(Long questionId) {
        // 获取分布式锁
        RLock rLock = redissonLockService.acquire(CacheLockConstants.QUESTION_ADD_LOCK, -1);
        // 获取锁失败跳过执行
        if (null == rLock) {
            return;
        }

        try {
            redisService.leftPushForList(CacheConstants.QUESTION_LIST, questionId);
        } catch (Exception e) {
            log.error("新增题目列表缓存失败！");
        } finally {
            // 解锁
            if (rLock.isHeldByCurrentThread() && rLock.isLocked()) {
                redissonLockService.releaseLock(rLock);
            }
        }
    }

    @Async(value = "threadPoolTaskExecutor")
    public void deleteCache(Long questionId) {
        // 获取分布式锁
        RLock rLock = redissonLockService.acquire(CacheLockConstants.QUESTION_DEL_LOCK, -1);
        // 获取失败跳过执行
        if (null == rLock) {
            return;
        }

        try {
            redisService.removeForList(CacheConstants.QUESTION_LIST, questionId);
        } catch (Exception e) {
            log.error("删除题目列表缓存失败");
        } finally {
            // 解锁
            if (rLock.isHeldByCurrentThread() && rLock.isLocked()) {
                redissonLockService.releaseLock(rLock);
            }
        }

    }
}
